import React, { useState } from 'react';
import { Form, Input, Button, Toast, NavBar } from 'antd-mobile';
import { useNavigate, Link } from 'react-router-dom';
import { login } from '../../../services/auth';
import styles from './index.module.css';

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: { username: string; password: string }) => {
    try {
      setLoading(true);
      const response = await login(values);
      if (response && response.token) {
        Toast.show({
          icon: 'success',
          content: '登录成功',
        });
        navigate('/');
      } else {
        throw new Error('登录失败：无效的响应数据');
      }
    } catch (error: any) {
      const errorMsg = error.response?.data?.message || error.message || '登录失败，请重试';
      Toast.show({
        icon: 'fail',
        content: errorMsg,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginPage}>
      <NavBar onBack={() => navigate(-1)}>用户登录</NavBar>

      <div className={styles.formContainer}>
        <h2 className={styles.title}>旅游日记</h2>
        <p className={styles.subtitle}>记录旅行，分享快乐</p>

        <Form
          layout='vertical'
          onFinish={onFinish}
          footer={
            <Button block type='submit' color='primary' loading={loading}>
              登录
            </Button>
          }
        >
          <Form.Item
            name='username'
            label='用户名'
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder='请输入用户名' />
          </Form.Item>

          <Form.Item
            name='password'
            label='密码'
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input placeholder='请输入密码' type='password' />
          </Form.Item>
        </Form>

        <div className={styles.registerLink}>
          <span>还没有账号？</span>
          <Link to="/auth/register">立即注册</Link>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;